import 'package:flutter/material.dart';
import '../model/baby.dart';
import '../service/database_service.dart';
import '../widgets/feeding_stats.dart';
import '../widgets/gradient_app_bar.dart';
import '../widgets/neumorphic_appbar.dart';
import '../widgets/weight_stats.dart';
import '../widgets/temperature_stats.dart';
import '../widgets/sleep_stats.dart';
import 'dart:io';

class StatisticsTab extends StatefulWidget {
  @override
  _StatisticsTabState createState() => _StatisticsTabState();
}

class _StatisticsTabState extends State<StatisticsTab> {
  Baby? _selectedBaby;
  List<Baby> _babies = [];
  String _selectedType = '喂养'; // Default type
  final List<String> _types = ['喂养', '体重', '体温', '睡眠'];
  DateTimeRange _dateRange = DateTimeRange(
    start: DateTime.now().subtract(const Duration(days: 30)),
    end: DateTime.now(),
  );

  @override
  void initState() {
    super.initState();
    _loadBabies();
  }

  Future<void> _loadBabies() async {
    try {
      final babies = await DatabaseService().getAllBabies();
      final defaultBaby = await DatabaseService().getDefaultBaby();
      setState(() {
        _babies = babies;
        _selectedBaby =
            defaultBaby ?? (babies.isNotEmpty ? babies.first : null);
      });
    } catch (e) {
      debugPrint('Error loading babies: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text("数据统计"),
        actions: [
          PopupMenuButton<String>(
            tooltip: '筛选',
            icon: Stack(
              children: [
                const Icon(Icons.filter_list),
                if (_dateRange.start !=
                        DateTime.now().subtract(const Duration(days: 30)) ||
                    _dateRange.end != DateTime.now())
                  Positioned(
                    right: 0,
                    top: 0,
                    child: Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.primary,
                        shape: BoxShape.circle,
                      ),
                    ),
                  ),
              ],
            ),
            itemBuilder:
                (context) => [
                  PopupMenuItem(child: Text('数据类型'), enabled: false),
                  ..._types.map(
                    (type) => CheckedPopupMenuItem(
                      checked: _selectedType == type,
                      value: 'type:$type',
                      child: Text(type),
                    ),
                  ),
                  const PopupMenuDivider(),
                  PopupMenuItem(child: Text('时间范围'), enabled: false),
                  PopupMenuItem(
                    value: 'date',
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '${_dateRange.start.toString().substring(0, 10)} - '
                          '${_dateRange.end.toString().substring(0, 10)}',
                        ),
                        Icon(Icons.calendar_today, size: 18),
                      ],
                    ),
                  ),
                ],
            onSelected: (value) async {
              if (value.startsWith('type:')) {
                setState(() {
                  _selectedType = value.substring(5);
                });
              } else if (value == 'date') {
                await _selectDateRange(context);
              }
            },
          ),
          const SizedBox(width: 8),
        ],
      ),
      body:
          _selectedBaby == null
              ? const Center(child: CircularProgressIndicator())
              : _buildStats(),
    );
  }

  Widget _buildStats() {
    switch (_selectedType) {
      case '喂养':
        return FeedingStats(babyId: _selectedBaby!.id, dateRange: _dateRange);
      case '体重':
        return WeightStats(babyId: _selectedBaby!.id, dateRange: _dateRange);
      case '体温':
        return TemperatureStats(
          babyId: _selectedBaby!.id,
          dateRange: _dateRange,
        );
      case '睡眠':
        return SleepStats(babyId: _selectedBaby!.id, dateRange: _dateRange);
      default:
        return const Center(child: Text('未知类型'));
    }
  }

  Future<void> _selectDateRange(BuildContext context) async {
    final picked = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
      initialDateRange: _dateRange,
    );
    if (picked != null) {
      setState(() {
        _dateRange = picked;
      });
    }
  }
}
